<template>
  <el-card class="swiper-container">
    <template #header>
      <div class="header">
        <el-button type="primary" :icon="Plus" @click="handleAdd">增加</el-button>
        <el-popconfirm title="确定删除吗？" confirmButtonText='确定' cancelButtonText='取消' @confirm="handleDelete">
          <template #reference>
            <el-button type="danger" :icon="Delete">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
    </template>
    <el-table :load="state.loading" ref="multipleTable"
      :data="state.tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" tooltip-effect="dark"
      style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="轮播图" width="300">
        <template #default="scope">
          <img style="width: 140px;height: 140px" :src="scope.row.carouselUrl" alt="轮播图">
        </template>
      </el-table-column>
      <el-table-column label="跳转链接">
        <template #default="scope">
          <a target="_blank" :href="scope.row.redirectUrl">{{ scope.row.redirectUrl }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="carouselRank" label="排序值" width="250">
      </el-table-column>
      <el-table-column prop="createTime" label="添加时间" width="200">
      </el-table-column>
    </el-table>
    <div class="pages">
      <div class="page_wrap">
        <span class="page_span1">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="state.tableData.length">
          </el-pagination>
        </span>
      </div>
    </div>
  </el-card>
  <el-dialog v-model="dialogVisible" title="添加轮播图" width="30%" style="height: 450px;">
    <div style="text-align: center;">
      <el-upload class="avatar-uploader" action="http://localhost:8080/goods/upload" :show-file-list="false"
        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </div><br><br>
    排序值<el-input v-model="input" placeholder="请输入排序值" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script  lang="ts"  setup>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { ElMessage, UploadProps } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

let dialogVisible = ref(false)
const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  currentPage: 1,
  pageSize: 10,
  type: 'add', // 操作类型,
  multipleSelection: [], // 选中项
  total: 0, // 总条数
})

onMounted(() => {
  getCarousels()
})
const currentPage = ref(1)
const total = ref(0)
const pageSize = ref(10)
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  currentPage.value = 1;
  pageSize.value = val;
}

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
}
// 获取轮播图列表
const getCarousels = () => {
  state.loading = true
  axios.post('http://localhost:8080/goods/carousel').then(res => {
    state.tableData = res.data
    state.loading = false
  })
}
// 添加轮播项
const handleAdd = () => {
  dialogVisible.value = true
}
const input = ref('')
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  imageUrl.value = response
  console.log(response);
  // axios.post('http://localhost:8080/user/change-avatar', { email: user.userInfo.email, avatar: user.userInfo.avatar }).then(resp => {
  //   ElMessage({
  //     message: '修改成功',
  //     type: 'success',
  //   })
  // })
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('必须是jpeg文件!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}
const submit = () => {
  dialogVisible.value = false
  axios.post('http://localhost:8080/goods/addCarousel', {
    "carouselUrl": imageUrl.value,
    "carouselRank": input.value
  }).then(resp => {
    getCarousels()
    imageUrl.value = ''
    input.value = ''
  })
}
// 选中之后的change方法，一旦选项有变化，就会触发该方法。
const handleSelectionChange = (val) => {
  state.multipleSelection = val
}
// 批量删除
const handleDelete = () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择项')
    return
  }
  state.multipleSelection.forEach(item => {
    axios.post('http://localhost:8080/goods/updateCarousel/' + item.carouselId).then(resp => {
      getCarousels()
    })
  })
}

</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>